#include "calServer.hpp"
#include <memory>

using namespace server;
using namespace std;

static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n\n";
}

// 回调函数
// req：里面一定是我们处理好的一个完整的请求对象
// resp:根据req,进行业务处理，填充resp，不用管理任何读取和写入，序列化反序列化细节
bool cal(const Request &req, Response &resp)
{
    std::cout<<"业务处理func：x:"<<req._x<<" y:"<<req._y<<" op:"<<req._op<<std::endl;

    // 初始化resp
    resp._exitcode = OK;
    resp._result = OK;
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;

        break;
    case '*':
        resp._result = req._x * req._y;

        break;
    case '/':
    {
        if (req._y == 0)
        {
            resp._exitcode = DIV_ZERO;
        }
        else
        {
            resp._result = req._x / req._y;
        }
    }
    break;
    case '%':
      {
        if (req._y == 0)
        {
            resp._exitcode = MOD_ZERO;
        }
        else
        {
            resp._result = req._x % req._y;
        }
    }
        break;
    default:
        resp._exitcode = OP_ERROR;
        break;
    }
    std::cout<<"func业务处理：result:"<<resp._result<<" exitcode:"<<resp._exitcode<<std::endl;
    return true;
}

// tcp服务器，启动上和udp server一模一样
// ./tcpserver local_port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    unique_ptr<CalServer> tsvr(new CalServer(port));
    tsvr->initServer();
    tsvr->start(cal);
    return 0;
}
